package org.dcarew.stripjar;

import org.kohsuke.args4j.CmdLineException;

import java.io.IOException;

public class Main {

  public static String getVersion() {
    final String fallbackVersion = "0.0.0";

    Package analyzerPackage = Main.class.getPackage();

    if (analyzerPackage.getImplementationVersion() == null) {
      return fallbackVersion;
    } else {
      return analyzerPackage.getImplementationVersion();
    }
  }

  public static void main(String[] args) throws IOException {
    StripperOptions options = new StripperOptions(args);

    try {
      options.parse();
    } catch (CmdLineException e) {
      System.out.println(e.getMessage());
      showHelp(options);
      exit(1);
    }

    if (options.getShowHelp()) {
      printVersion();
      System.out.println();
      showHelp(options);
      exit(0);
    }

    if (options.getShowVersion()) {
      printVersion();
      exit(0);
    }

    if (options.getFile() == null) {
      System.out.println("No input file passed to stripjar.");
      System.out.println();
      showHelp(options);
      exit(1);
    }

    Stripper stripper = new Stripper(
        options.getFile(),
        options.getOutFile(),
        options.getReorderFile());

    if (options.getNoStrip() != null) {
      stripper.setNoStrip(options.getNoStrip());
    }

    stripper.strip();
  }

  private static void exit(int exitCode) {
    System.exit(exitCode);
  }

  private static void printVersion() {
    System.out.println("stripjar version " + getVersion());
  }

  private static void showHelp(StripperOptions options) {
    System.out.println("Usage:");
    System.out.println(" stripjar [options] <file>");
    System.out.println();
    System.out.println("Options:");
    options.printUsage(System.out);
  }

}
